﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Linq;
using Core.Domain.Entities;
using Core.Domain.Enums;
using Core.Interfaces;
using Community = DataXml.CommunityFiles.Community;

namespace DataXml
{
  internal static class XmlHelper
  {
    public static ICommunity ReadCommunity(string fileName)
    {
      var community = new Community();

      var x = XDocument.Load(fileName);
      var root = x.Root;
      if (root == null) return community;

      community.Name = root.Attribute("Name").Value;

      foreach (var person in root.Elements())
      {
        community.People.Add(new Person
                               {
                                 FirstName = person.Attribute("FName").Value(),
                                 LastName = person.Attribute("LName").Value(),
                                 AgeGroup = ConvertAge(person.Attribute("AgeGroup").Value()),
                                 ElectionParticipationMethod = ConvertVote(person.Attribute("Voted").Value())

                               }
          );
      }
      return community;
    }

    private static string Value(this XAttribute input)
    {
      return input == null ? string.Empty : input.Value;
    }


    private static ElectionParticipationMethod ConvertVote(string xmlVoted)
    {
      switch (xmlVoted)
      {
        default:
        case "No":
          return ElectionParticipationMethod.NotSubmitted;

        case "VotedInPerson":
          return ElectionParticipationMethod.VotedInPerson;

        case "DroppedOff":
          return ElectionParticipationMethod.DroppedOff;

        case "Mailed":
          return ElectionParticipationMethod.MailedIn;

      }
    }

    private static AgeGroup ConvertAge(string xmlAgeGroup)
    {
      switch (xmlAgeGroup)
      {
        case "Adult":
          return Core.Domain.Enums.AgeGroup.Adult;
        case "Youth":
          return Core.Domain.Enums.AgeGroup.Youth;
        case "PreYouth":
        case "Pre-Youth":
          return Core.Domain.Enums.AgeGroup.JuniorYouth;
        case "Child":
          return Core.Domain.Enums.AgeGroup.Child;
        default:
          return Core.Domain.Enums.AgeGroup.Unknown;
      }
    }

    public static T ReadXml<T>(Stream stream)
    {
      if (stream != null)
      {
        var serializer = new DataContractSerializer(typeof (T));
        return (T) serializer.ReadObject(stream);
      }
      return default(T);
    }
  }
}